package team;
import javax.swing.*;

import autoproject.SpringUtilities;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

/**
 * Edit Frame for Cars
 * @author jerry
 *
 */


public class AutoEditFrame extends JFrame{
	
	private final JFrame frame = this;
	
	/**
	 * Construct a AutoEditFrame
	 */
	public AutoEditFrame(String[] editInfo, final boolean authorized) {
		setLayout(new GridLayout(2, 1));
		final JTextField[] inputArray = new JTextField[7];
		final String[] originalInfo = editInfo;
		
		//set up the text field panel
		String[] options = {"AutoMaker: ", "Model: ", "Year: ", "Description: ", "Liter: ", "Engine: ", "Cubic"};
		JPanel textPanel = new JPanel(new SpringLayout());
		for (int i = 0; i < options.length; i++) {
			JLabel l = new JLabel(options[i], JLabel.TRAILING);
			textPanel.add(l);
			JTextField textField = new JTextField(10);
			inputArray[i] = textField;
			l.setLabelFor(textField);
			textPanel.add(textField);
			textField.setText(editInfo[i]);
		}
		SpringUtilities.makeCompactGrid(textPanel, options.length, 2, 6, 6, 6, 6);
		
		//button panel
		JPanel btnPanel = new JPanel(new FlowLayout());
		JButton updateBtn = new JButton("Update");
		JButton backBtn = new JButton("Back");
		btnPanel.add(updateBtn);
		btnPanel.add(backBtn);
		
		//add button acitonListener
		updateBtn.addActionListener(new ActionListener() {
			@Override 
			public void actionPerformed(ActionEvent e) {
				String[] updatedInfo = new String[7];
				for (int i = 0; i < inputArray.length; i++) {
					System.out.print(inputArray[i].getText() + " ");
					updatedInfo[i] = inputArray[i].getText();
				}
				System.out.println();
				originalInfo[0] = AutoMaker.makerTable.get(originalInfo[0]);
				if (AutoMaker.makerTable.containsKey(updatedInfo[0]))
					updatedInfo[0] = AutoMaker.makerTable.get(updatedInfo[0]);
				else {
					AutoMaker.addMaker(updatedInfo[0], "OTR" + updatedInfo[0]);
					updatedInfo[0] = AutoMaker.makerTable.get(updatedInfo[0]);
				}
				boolean updated = Result.editAuto(updatedInfo, originalInfo);
				if (updated) System.out.println("updated");
			}
		});
		backBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				AutoMakerFrame makerFrame = new AutoMakerFrame(new InitialFrame(), authorized);
				frame.dispose();
			}
		});
		
		this.setTitle("Edit Auto");
		this.setSize(800,600);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		textPanel.setOpaque(true);
//		add(textPanel, BorderLayout.CENTER);
		add(textPanel);
		textPanel.setBorder(BorderFactory.createTitledBorder("Edit Auto: "));
//		add(btnPanel, BorderLayout.SOUTH);
		add(btnPanel);
		
//		this.pack();
		this.setVisible(true);
	}
}
